package priv.lhy.log.util;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : lihy
 * @date : 2021/8/5 14:58
 */
public class MethodInvocationUtil {

    /**
     * 获取参数名称与值的map
     *
     * @param invocation
     * @return
     */
    public static Map<String, Object> getParamsByInvocation(MethodInvocation invocation) {
        Parameter[] parameters = invocation.getMethod().getParameters();
        //参数名
        String[] paramNames = Arrays.stream(parameters).map(Parameter::getName).toArray(String[]::new);
        Object[] paramValues = invocation.getArguments();

        Map<String, Object> requestParams = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            if (value instanceof HttpServletResponse || value instanceof HttpServletRequest) {
                value = null;
            }

            //如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                value = file.getOriginalFilename();  //获取文件名
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }


}
